//
//  HMAudioPlayer.m
//  MOMU
//
//  Created by mynSoo on 2017/1/3.
//  Copyright © 2017年 mynSoo. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "HMAudioPlayer.h"

@interface HMAudioPlayer()

/**
 播放器
 */
@property (nonatomic, strong) AVPlayer *player;

/**
 媒体文件播放总时长
 */
@property (nonatomic, assign) float durationTime;

/**
 媒体文件现在播放时间
 */
@property (nonatomic, assign) float currentTime;

/**
 播放刷新计时器
 */
//@property (nonatomic, weak) NSTimer *timer;

/**
 URL缓存
 */
@property (nonatomic, strong) NSArray<NSURL *>* urlArray;

/**
 正在指向的URL下标
 */
@property (nonatomic, assign) NSInteger index;

/**
 播放速率
 */
@property (nonatomic, assign) float rate;

/**
 声音大小
 */
@property (nonatomic, assign) float volume;
@end

@implementation HMAudioPlayer

-(void)setRate:(float)rate
{
    self.player.rate = rate;
}
- (void)setVolume:(float)volume
{
    self.player.volume = volume;
}

- (float)durationTime
{
    return CMTimeGetSeconds(self.player.currentItem.duration);
}

- (float)currentTime
{
    return CMTimeGetSeconds(self.player.currentItem.currentTime);
    
}

// 初始化方法
static id _instance;

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        [self installPlayer];
    }
    return self;
    
}

+ (instancetype)sharePlayer
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self new];

    });
    return _instance;
}

// 设置播放列表
- (void)setPlayListWithURL:(NSURL *)url
{
    self.urlArray = @[url];
};

- (void)setPlayListWithURLArray:(NSArray<NSURL *> *)urlArray
{
    self.urlArray = urlArray;
};

// 配置播放器
- (void)installPlayer
{
    self.player = [[AVPlayer alloc]init];
    
    self.player.volume = 0.5;
    
    // self.player.status;
}
- (void)play
{
    
}
/**
 播放指定下标的URL

 @param index 指定下标
 */
- (void)playWithIndex:(NSInteger)index
{
    // 下标安全判断
    if(self.index < 0 || self.index > self.urlArray.count)
    {
        return;
    }
    // 播放指定下标的URL
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:self.urlArray[index]];
    
    [self.player replaceCurrentItemWithPlayerItem:item];
    
}

/**
 暂停
 */
- (void)pause
{
    [self.player pause];
}

/**
 播放上一个
 */
- (void)playPrevious
{
    self.index = (self.index + self.urlArray.count - 1) % self.urlArray.count;
    
    [self playWithIndex:self.index];
}

/**
 播放下一个
 */
- (void)playNext
{
    self.index = (self.index + 1) % self.urlArray.count;
    
    [self playWithIndex:self.index];
}

/**
 播放item

 @param item 要不放的item
 */
- (void)playWithItem:(AVPlayerItem *)item
{
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self.player play];
}

@end
